import FormItem from './FormItem';
import OceanComponent from './OceanComponent';
import OForm from '../../components/Form.vue';
import FormItems from './FormItems';
import { FormItemProps } from '../common/props';

interface IForm<T> {
  item(label: string, key: keyof T): FormItem<T>;
  setModel(model: T): this;
  clearModel(): this;
}

class Form<T = any> extends OceanComponent<TFormProps<T>> implements IForm<T> {
  model: T;
  formItems: FormItems<T>;
  constructor(attrs?: TFormProps<T>) {
    super(OForm, attrs, {
      model: {}
    } as any);
    this.model = this.attrs.model;
    this.formItems = new FormItems<T>({
      model: this.model,
      cols: this.attrs.cols,
      collapsed: this.attrs.collapsed,
      collapsedRows: this.attrs.collapsedRows
    });
  }
  item(label: string, key: keyof T, props?: FormItemProps): FormItem<T> {
    return this.formItems.item(label, key, props);
  }
  setModel(model: Partial<T>) {
    Object.assign(this.model, model);
    return this;
  }
  clearModel() {
    for (let k in this.model) {
      this.model[k] = '' as any;
    }
    return this;
  }
  getAttrs() {
    return [this.model, this.attrs];
  }
  validate(callback?: Function) {
    const _ref = this.getRef();
    if (_ref) {
      return _ref.validate(callback);
    }
    return Promise.reject();
  }

  restoreValidation() {
    const _ref = this.getRef();
    if (_ref) {
      return _ref.restoreValidation();
    }
  }

  get items() {
    return this.formItems.items;
  }
}
export default Form;
